package com.tianji.learning.mq;

import com.tianji.api.dto.leanring.LearningRecordFormDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.mq.message.LearningRecordMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Covey
 * 在MQ监听器调用的方法中，UserContext.getUser() 无法获取到用户信息，因为：
 *      线程上下文丢失：MQ消费者在单独的线程中执行，用户上下文信息没有传递过来
 *      异步调用：MQ消息处理是异步的，原始请求的ThreadLocal信息不会自动传递
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearningRecordProducer {

    private final RabbitTemplate rabbitTemplate;

    public void sendLearningRecord(LearningRecordFormDTO recordDTO) {
        log.debug("发送学习记录消息到MQ: {}", recordDTO);
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUser();
            // 创建包含用户ID的消息对象
            LearningRecordMessage message = new LearningRecordMessage(userId, recordDTO);
            rabbitTemplate.convertAndSend(
                    MqConstants.Exchange.LEARNING_EXCHANGE,
                    MqConstants.Key.LEARNING_RECORD_KEY,
                    message
            );
        } catch (Exception e) {
            log.error("发送学习记录消息到MQ失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送学习记录消息失败", e);
        }
    }
}